package indi.kider.server.employee.service;

import com.google.common.base.Strings;
import indi.kider.common.constant.AppUserType;
import indi.kider.common.constant.EmployeeRoleCons;
import indi.kider.common.constant.StatusCons;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apabus.RentOutline;
import indi.kider.common.model.employee.*;
import indi.kider.server.apabus.mapper.RentOutlineMapper;
import indi.kider.server.employee.mapper.EmployeeMapper;
import indi.kider.server.employee.mapper.TenantMapper;
import indi.kider.server.employee.mapper.WaiterMapper;
import indi.kider.server.employee.mapper.WorkerMapper;
import indi.kider.server.employee.model.PwdChanger;
import indi.kider.server.employee.service.related.AuthcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.vankid.common.constant.HttpCode;
import pers.vankid.common.model.base.CommonResponse;
import pers.vankid.common.utils.page.PageRequest;
import pers.vankid.common.utils.page.PageResponse;
import pers.vankid.common.utils.page.PageUtil;

import java.util.List;

/**
 * Created by shixj on 2018/4/23.
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private WaiterMapper waiterMapper;
    @Autowired
    private WorkerMapper workerMapper;
    @Autowired
    private AuthcService authcService;
    @Autowired
    private TenantService tenantService;
    @Autowired
    private UserService userService;
    @Autowired
    private RentOutlineMapper rentOutlineMapper;
    @Override
    public List<Employee> getUsersToLogin(String loginName) {
        return employeeMapper.getUsersToLogin(loginName);
    }

    @Override
    public List<Employee> getUsersByLoginNameWithLike(String loginName) {
        return employeeMapper.getUsersByLoginNameWithLike(loginName);
    }

    @Override
    public Employee getEmployeeById(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public Employee add(Employee employee) throws Exception {
        if (employee != null) {
            if (employee.getId() == null || employee.getId().equals(0L)) {
                employee.setId(null);
                if (Strings.isNullOrEmpty(employee.getPwd()))
                    employee.setPwd("123456");

                //存在的手机号=======
                String phone = employee.getPhone();
                Employee temp = new Employee();
                temp.setPhone(phone);
                temp.setState(StatusCons.VALID);
                int count = employeeMapper.selectCount(temp);
                if(count == 0 ){
                    employee.setState(StatusCons.VALID);
                    employeeMapper.insert(employee);
                }else{
                    throw new Exception("手机号码"+phone+"已被注册!");
                }
            }
        }
        employee.setPwd(null);
        return employee;
    }

    private boolean exists(Employee employee) {
        Employee temp = new Employee();
        temp.setState(StatusCons.VALID);
        temp.setPhone(employee.getPhone());
        int count = employeeMapper.selectCount(temp);
        if(count == 0 ){
            return  false;
        }else if(count == 1 ){
            Employee update = employeeMapper.selectOne(temp);
            if(update.getId() == employee.getId()){
                return  false;
            }else{
                return  true;
            }
        }
        return  true;
    }

    @Transactional
    @Override
    public Employee modify(Employee employee) throws Exception {
        if (employee != null && employee.getId() != null && employee.getId() > 0L) {
            if(exists(employee))
                throw new Exception("手机号码"+employee.getPhone()+"已被注册");
            employee.setPwd(null);
            employeeMapper.updateByPrimaryKeySelective(employee);
            Employee employee1 = employeeMapper.selectByPrimaryKey(employee.getId());
            authcService.updateLoginEmployee(employee1);
            employee1.setPwd(null);
            return employee1;
        }
        return employee;
    }

    @Transactional
    @Override
    public CommonResponse modifyPwd(PwdChanger pwdChanger) {
        CommonResponse commonResponse = new CommonResponse();
        if (pwdChanger != null && pwdChanger.getId() > 0) {
            Employee employeeOld = employeeMapper.selectByPrimaryKey(pwdChanger.getId());
            if (pwdChanger.getOldPwd() != null) {
                if (employeeOld.getPwd().equals(pwdChanger.getOldPwd())) {
                    Employee employeeNew = new Employee();
                    employeeNew.setId(pwdChanger.getId());
                    employeeNew.setPwd(pwdChanger.getNewPwd());
                    employeeMapper.updateByPrimaryKeySelective(employeeNew);
                    Employee employee1 = employeeMapper.selectByPrimaryKey(pwdChanger.getId());
                    authcService.updateLoginEmployee(employee1);
                    commonResponse.setStatus(HttpCode.SUCCESS_UPDATE);
                    commonResponse.setMsg("密码修改成功！");
                } else {
                    commonResponse.setStatus(HttpCode.ERROR_BAD_REQUEST);
                    commonResponse.setMsg("请确认原密码！");
                }
            } else {
                commonResponse.setStatus(HttpCode.ERROR_BAD_REQUEST);
                commonResponse.setMsg("请输入原密码！");
            }
        } else {
            commonResponse.setStatus(HttpCode.ERROR_BAD_REQUEST);
            commonResponse.setMsg("请求异常！");
        }
        return commonResponse;
    }

    @Transactional
    @Override
    public void del(Long id) {
        if (id != null && id > 0L)
            employeeMapper.deleteByPrimaryKey(id);
    }

    /**
     * 删除合作用户的同时删除rent_outline
     * @param id
     */
    @Transactional
    @Override
    public void delHzById(Long id) {
        if (id != null && id > 0L) {
            Employee ee = employeeMapper.selectByPrimaryKey(id);
            RentOutline rentOutline = new RentOutline();
            rentOutline.setEnterprise(ee.getEnterpriseId());
            rentOutlineMapper.delete(rentOutline);
            employeeMapper.deleteByPrimaryKey(id);
        }
    }


    @Override
    public PageResponse getEmployees(Employee employee, int num, int size) {
        PageUtil.start(num, size);
        return PageUtil.getPageResponse(employeeMapper.select(employee));
    }

    @Override
    public PageResponse getEmployees(PageRequest<Employee> request) {
        PageUtil.start(request);
        return PageUtil.getPageResponse(employeeMapper.getEmployeeList(request.getQuery()));
    }
    @Override
    public PageResponse getHzEmployees(PageRequest<Employee> request,Employee employee) {
        Employee query = request.getQuery();
        query.setEnterpriseId(employee.getEnterpriseId());
        PageUtil.start(request);
        return PageUtil.getPageResponse(employeeMapper.getHzEmployees(query));
    }


    @Override
    public List<Employee> getEmployeesNoPage(Long enId) {
        Employee employee = new Employee();
        employee.setEnterpriseId(enId);
        employee.setRoles(EmployeeRoleCons.FIVE);
        return employeeMapper.select(employee);
    }

}
